<template>
  <div class="operation-log-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>操作日志</span>
        </div>
      </template>

      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="操作人">
          <el-input v-model="searchForm.username" placeholder="请输入操作人" clearable />
        </el-form-item>
        <el-form-item label="操作描述">
          <el-input v-model="searchForm.operation" placeholder="请输入操作描述" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="logList" style="width: 100%"  border>
        <el-table-column type="index" label="序号" width="60" fixed align="center" />
        <el-table-column prop="username" label="操作人" width="120" align="center" />
        <el-table-column prop="operation" label="操作描述" show-overflow-tooltip width="180" align="center" />
        <el-table-column prop="method" label="请求方法" width="250" align="center" show-overflow-tooltip />
        <el-table-column prop="params" label="请求参数" width="250" align="center" show-overflow-tooltip />
        <el-table-column prop="time" label="耗时(ms)" width="100" align="center" />
        <el-table-column prop="ip" label="IP地址" width="150" align="center" />
        <el-table-column prop="url" label="请求URL" width="250" show-overflow-tooltip align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="errorMsg" label="错误信息" width="250" show-overflow-tooltip align="center" />
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ row.createTime ? new Date(row.createTime).toLocaleString() : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              v-if="hasPermission('system:log:delete')"
              type="danger"
              link
              @click="handleDelete(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :small="false"
        :disabled="false"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOperationLogPage, deleteOperationLog } from '@/api/log'
import { usePermission } from '@/hooks/usePermission'

interface OperationLog {
  id: number;
  username: string;
  operation: string;
  method: string;
  params: string;
  time: number;
  ip: string;
  url: string;
  status: number;
  errorMsg?: string;
  createTime: string;
}

const logList = ref<OperationLog[]>([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)

const searchForm = reactive({
  username: '',
  operation: '',
})

const { hasPermission } = usePermission()

const fetchOperationLogs = async () => {
  try {
    const res = await getOperationLogPage({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...searchForm,
    })
    if (res.code === 200) {
      logList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '获取日志失败')
    }
  } catch (error) {
    ElMessage.error('获取日志请求失败')
    console.error('Error fetching operation logs:', error)
  }
}

const handleSearch = () => {
  pageNum.value = 1
  fetchOperationLogs()
}

const resetSearch = () => {
  searchForm.username = ''
  searchForm.operation = ''
  pageNum.value = 1
  fetchOperationLogs()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchOperationLogs()
}

const handleCurrentChange = (val: number) => {
  pageNum.value = val
  fetchOperationLogs()
}

const handleDelete = (id: number) => {
  ElMessageBox.confirm(
    '确定要删除这条日志吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await deleteOperationLog(id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        await fetchOperationLogs()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

onMounted(async () => {
  await fetchOperationLogs()
})
</script>

<style scoped>
.operation-log-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 10px;
  border-radius: 4px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.el-table {
  margin-top: 20px;
}
</style>
